/**
 * MCP工具注册管理器
 * 解决组件中MCP工具注册时机问题
 */

class McpToolRegistry {
  constructor() {
    this.tools = []
    this.mcpService = null
    this.isReady = false
    this.retryTimers = new Map()
  }

  // 注册工具定义（在组件中调用）
  register(name, description, schema, handler) {
    const toolDefinition = {
      name,
      description,
      schema,
      handler,
      registered: false
    }

    this.tools.push(toolDefinition)
    console.log(`[MCP Registry] 工具定义已添加: ${name}`)

    // 如果MCP服务已就绪，立即注册
    if (this.isReady && this.mcpService) {
      this._registerTool(toolDefinition)
    }

    return toolDefinition
  }

  // 设置MCP服务（在MCP初始化后调用）
  setMcpService(mcpService) {
    this.mcpService = mcpService
    this.isReady = true
    console.log('[MCP Registry] MCP服务已设置，开始注册工具')

    // 注册所有待注册的工具
    this.tools.forEach(tool => {
      if (!tool.registered) {
        this._registerTool(tool)
      }
    })
  }

  // 内部注册工具方法
  _registerTool(toolDefinition) {
    if (!this.mcpService || !this.mcpService.mcpServer) {
      console.error('[MCP Registry] MCP服务未就绪，无法注册工具:', toolDefinition.name)
      return
    }

    try {
      this.mcpService.mcpServer.registerTool(
        toolDefinition.name,
        toolDefinition.description,
        toolDefinition.schema,
        toolDefinition.handler
      )

      toolDefinition.registered = true
      console.log(`[MCP Registry] 工具注册成功: ${toolDefinition.name}`)

      // 清除重试定时器
      if (this.retryTimers.has(toolDefinition.name)) {
        clearTimeout(this.retryTimers.get(toolDefinition.name))
        this.retryTimers.delete(toolDefinition.name)
      }
    } catch (error) {
      console.error(`[MCP Registry] 工具注册失败: ${toolDefinition.name}`, error)

      // 添加重试机制
      this._scheduleRetry(toolDefinition)
    }
  }

  // 重试注册机制
  _scheduleRetry(toolDefinition) {
    if (this.retryTimers.has(toolDefinition.name)) {
      return // 已有重试任务
    }

    const retryCount = this.retryTimers.get(`${toolDefinition.name}_count`) || 0
    if (retryCount >= 5) {
      console.error(`[MCP Registry] 工具注册重试次数超限: ${toolDefinition.name}`)
      return
    }

    const timer = setTimeout(() => {
      console.log(`[MCP Registry] 重试注册工具: ${toolDefinition.name} (${retryCount + 1}/5)`)
      this._registerTool(toolDefinition)

      const currentCount = this.retryTimers.get(`${toolDefinition.name}_count`) || 0
      this.retryTimers.set(`${toolDefinition.name}_count`, currentCount + 1)
    }, 1000 * (retryCount + 1))

    this.retryTimers.set(toolDefinition.name, timer)
  }

  // 获取已注册的工具列表
  getRegisteredTools() {
    return this.tools.filter(tool => tool.registered).map(tool => ({
      name: tool.name,
      description: tool.description
    }))
  }

  // 获取待注册的工具列表
  getPendingTools() {
    return this.tools.filter(tool => !tool.registered).map(tool => ({
      name: tool.name,
      description: tool.description
    }))
  }

  // 清理资源
  cleanup() {
    this.retryTimers.forEach(timer => clearTimeout(timer))
    this.retryTimers.clear()
    this.tools = []
    this.mcpService = null
    this.isReady = false
  }
}

// 创建全局单例
export const mcpToolRegistry = new McpToolRegistry()

// 导出注册函数，供组件使用
export function registerMcpTool(name, description, schema, handler) {
  return mcpToolRegistry.register(name, description, schema, handler)
}

export default mcpToolRegistry